"""
设备管理API端点
Device Management API Endpoints

为前端AddCameraModal组件提供设备和通道数据
"""
import logging
from datetime import datetime
from typing import List, Dict, Any, Optional
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel

from services.wvp_service_unified import get_unified_wvp_service
from database.simple_db import get_database_manager

logger = logging.getLogger(__name__)
router = APIRouter()

# 获取统一WVP服务和数据库管理器
wvp_service = get_unified_wvp_service()
db = get_database_manager()


class DeviceResponse(BaseModel):
    """设备响应模型"""
    deviceId: str
    name: str
    manufacturer: Optional[str] = "Unknown"
    model: Optional[str] = "Unknown"
    ip: Optional[str] = ""
    port: int = 5060
    online: bool = False
    status: str = "OFF"
    channelCount: int = 0
    description: Optional[str] = ""


class ChannelResponse(BaseModel):
    """通道响应模型"""
    channelId: str
    deviceId: str
    name: str
    status: str = "ON"
    online: bool = False
    rtspUrl: Optional[str] = ""
    longitude: float = 0.0
    latitude: float = 0.0
    description: Optional[str] = ""


@router.get("/list")
async def get_device_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(100, ge=1, le=1000, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    status: Optional[str] = Query(None, description="设备状态"),
    online: Optional[bool] = Query(None, description="在线状态")
):
    """
    获取设备列表
    为AddCameraModal组件提供设备数据，兼容WVP API格式
    """
    try:
        logger.info(f"获取设备列表请求: page={page}, size={size}, search={search}")
        
        # 首先尝试从本地数据库获取设备数据
        devices = []
        
        try:
            # 查询本地数据库中的摄像头，按设备ID分组
            query = """
                SELECT DISTINCT 
                    wvp_device_id as device_id,
                    name,
                    description,
                    status,
                    COUNT(*) as channel_count
                FROM cameras 
                WHERE wvp_device_id IS NOT NULL 
                AND wvp_device_id != ''
            """
            
            params = []
            
            if search:
                query += " AND (name LIKE ? OR description LIKE ?)"
                search_param = f"%{search}%"
                params.extend([search_param, search_param])
            
            if status:
                query += " AND status = ?"
                params.append(status)
            
            query += " GROUP BY wvp_device_id ORDER BY name"
            
            # 添加分页
            offset = (page - 1) * size
            query += f" LIMIT {size} OFFSET {offset}"
            
            local_devices = db.execute_query(query, params)
            
            logger.info(f"从本地数据库查询到 {len(local_devices)} 个设备")
            
            for device_data in local_devices:
                device = DeviceResponse(
                    deviceId=device_data['device_id'],
                    name=device_data['name'],
                    description=device_data.get('description', ''),
                    status=device_data.get('status', 'OFF'),
                    online=device_data.get('status', 'OFF').upper() == 'ON',
                    channelCount=device_data.get('channel_count', 0)
                )
                devices.append(device.dict())
            
        except Exception as e:
            logger.warning(f"从本地数据库获取设备失败: {e}")
        
        # 如果本地没有数据，尝试从Java后端WVP获取
        if not devices:
            logger.info("本地数据库无设备数据，尝试从Java后端WVP获取...")
            
            try:
                wvp_result = await wvp_service.get_camera_list(page=page, count=size)
                
                if wvp_result["success"]:
                    cameras = wvp_result["data"]["list"]
                    logger.info(f"从Java后端WVP获取到 {len(cameras)} 个摄像头")
                    
                    # 按设备ID分组
                    devices_map = {}
                    for camera in cameras:
                        device_id = camera["device_id"]
                        if device_id not in devices_map:
                            devices_map[device_id] = {
                                "deviceId": device_id,
                                "name": camera["name"].split("-")[0] if "-" in camera["name"] else camera["name"],
                                "manufacturer": camera.get("manufacturer", "Unknown"),
                                "model": camera.get("model", "Unknown"),
                                "ip": camera.get("ip_address", ""),
                                "port": camera.get("port", 5060),
                                "status": camera.get("status", "OFF"),
                                "online": camera.get("status", "OFF").upper() == "ON",
                                "channelCount": 0,
                                "description": f"WVP设备 {device_id}"
                            }
                        devices_map[device_id]["channelCount"] += 1
                    
                    devices = list(devices_map.values())
                    logger.info(f"转换为 {len(devices)} 个设备")
                
            except Exception as e:
                logger.warning(f"从Java后端WVP获取设备失败: {e}")
        
        # 计算总数（简化处理）
        total = len(devices)
        
        logger.info(f"最终返回 {len(devices)} 个设备")
        
        return {
            "code": 200,
            "msg": "查询成功",
            "total": total,
            "rows": devices
        }
        
    except Exception as e:
        logger.error(f"获取设备列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取设备列表失败: {str(e)}")


@router.get("/{device_id}/channels")
async def get_device_channels(
    device_id: str,
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(100, ge=1, le=1000, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    status: Optional[str] = Query(None, description="通道状态")
):
    """
    获取设备通道列表
    为AddCameraModal组件提供通道数据，兼容WVP API格式
    """
    try:
        logger.info(f"获取设备 {device_id} 的通道列表")
        
        channels = []
        
        # 首先尝试从本地数据库获取通道数据
        try:
            query = """
                SELECT 
                    id,
                    name,
                    wvp_device_id,
                    wvp_channel_id,
                    status,
                    rtsp_url,
                    longitude,
                    latitude,
                    description
                FROM cameras 
                WHERE wvp_device_id = ?
            """
            
            params = [device_id]
            
            if search:
                query += " AND (name LIKE ? OR description LIKE ?)"
                search_param = f"%{search}%"
                params.extend([search_param, search_param])
            
            if status:
                query += " AND status = ?"
                params.append(status)
            
            query += " ORDER BY name"
            
            # 添加分页
            offset = (page - 1) * size
            query += f" LIMIT {size} OFFSET {offset}"
            
            local_channels = db.execute_query(query, params)
            
            logger.info(f"从本地数据库查询到 {len(local_channels)} 个通道")
            
            for channel_data in local_channels:
                channel = ChannelResponse(
                    channelId=channel_data.get('wvp_channel_id', str(channel_data['id'])),
                    deviceId=channel_data['wvp_device_id'],
                    name=channel_data['name'],
                    status=channel_data.get('status', 'ON'),
                    online=channel_data.get('status', 'OFF').upper() == 'ON',
                    rtspUrl=channel_data.get('rtsp_url', ''),
                    longitude=float(channel_data.get('longitude', 0.0)),
                    latitude=float(channel_data.get('latitude', 0.0)),
                    description=channel_data.get('description', '')
                )
                channels.append(channel.dict())
            
        except Exception as e:
            logger.warning(f"从本地数据库获取通道失败: {e}")
        
        # 如果本地没有数据，尝试从Java后端WVP获取
        if not channels:
            logger.info(f"本地数据库无设备 {device_id} 的通道数据，尝试从Java后端WVP获取...")
            
            try:
                wvp_result = await wvp_service.get_camera_list(page=1, count=1000)
                
                if wvp_result["success"]:
                    cameras = wvp_result["data"]["list"]
                    
                    # 筛选该设备的通道
                    device_cameras = [c for c in cameras if c["device_id"] == device_id]
                    logger.info(f"从Java后端WVP获取到设备 {device_id} 的 {len(device_cameras)} 个通道")
                    
                    for camera in device_cameras:
                        channel = ChannelResponse(
                            channelId=camera["channel_id"],
                            deviceId=camera["device_id"],
                            name=camera["name"],
                            status=camera.get("status", "ON"),
                            online=camera.get("status", "OFF").upper() == "ON",
                            rtspUrl=f"rtsp://localhost:554/rtp/{camera['device_id']}_{camera['channel_id']}",
                            longitude=float(camera.get("longitude", 0.0)),
                            latitude=float(camera.get("latitude", 0.0)),
                            description=f"WVP通道 {camera['channel_id']}"
                        )
                        channels.append(channel.dict())
                
            except Exception as e:
                logger.warning(f"从Java后端WVP获取通道失败: {e}")
        
        # 计算总数
        total = len(channels)
        
        logger.info(f"最终返回设备 {device_id} 的 {len(channels)} 个通道")
        
        return {
            "code": 200,
            "msg": "查询成功",
            "total": total,
            "rows": channels
        }
        
    except Exception as e:
        logger.error(f"获取设备通道列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取设备通道列表失败: {str(e)}")


@router.get("/{device_id}")
async def get_device_detail(device_id: str):
    """获取设备详情"""
    try:
        logger.info(f"获取设备 {device_id} 详情")
        
        # 首先尝试从本地数据库获取
        try:
            query = """
                SELECT 
                    wvp_device_id as device_id,
                    name,
                    description,
                    status,
                    COUNT(*) as channel_count
                FROM cameras 
                WHERE wvp_device_id = ?
                GROUP BY wvp_device_id
            """
            
            local_device = db.execute_query(query, [device_id])
            
            if local_device:
                device_data = local_device[0]
                device = DeviceResponse(
                    deviceId=device_data['device_id'],
                    name=device_data['name'],
                    description=device_data.get('description', ''),
                    status=device_data.get('status', 'OFF'),
                    online=device_data.get('status', 'OFF').upper() == 'ON',
                    channelCount=device_data.get('channel_count', 0)
                )
                
                return {
                    "code": 200,
                    "msg": "查询成功",
                    "data": device.dict()
                }
        
        except Exception as e:
            logger.warning(f"从本地数据库获取设备详情失败: {e}")
        
        # 如果本地没有数据，从Java后端WVP获取
        try:
            wvp_result = await wvp_service.get_camera_list(page=1, count=1000)
            
            if wvp_result["success"]:
                cameras = wvp_result["data"]["list"]
                device_cameras = [c for c in cameras if c["device_id"] == device_id]
                
                if device_cameras:
                    first_camera = device_cameras[0]
                    device = DeviceResponse(
                        deviceId=device_id,
                        name=first_camera["name"].split("-")[0] if "-" in first_camera["name"] else first_camera["name"],
                        manufacturer=first_camera.get("manufacturer", "Unknown"),
                        model=first_camera.get("model", "Unknown"),
                        ip=first_camera.get("ip_address", ""),
                        port=first_camera.get("port", 5060),
                        status=first_camera.get("status", "OFF"),
                        online=first_camera.get("status", "OFF").upper() == "ON",
                        channelCount=len(device_cameras),
                        description=f"WVP设备 {device_id}"
                    )
                    
                    return {
                        "code": 200,
                        "msg": "查询成功",
                        "data": device.dict()
                    }
        
        except Exception as e:
            logger.warning(f"从Java后端WVP获取设备详情失败: {e}")
        
        raise HTTPException(status_code=404, detail=f"设备 {device_id} 不存在")
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取设备详情失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取设备详情失败: {str(e)}")


@router.get("/{device_id}/status")
async def get_device_status(device_id: str):
    """获取设备在线状态"""
    try:
        # 简化实现，返回基本状态信息
        return {
            "code": 200,
            "msg": "查询成功",
            "data": {
                "online": False,
                "last_heartbeat": None,
                "status": "offline"
            }
        }
        
    except Exception as e:
        logger.error(f"获取设备状态失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取设备状态失败: {str(e)}")